package task4;

import java.util.Random;

public class QueueOfThreads {
	
	private final static int QUANTITY_OF_THREADS = 10;
	private final static int THREAD_WAITING_CEILING = 3000;
	
	public volatile Integer threadToPrint = new Integer(0);
	public Object lock = new Object();
	
	class PrintingThread implements Runnable {
		
		int myID;		
		
		public PrintingThread(int ID) {
			myID = ID;			
		}
		
		public void run() {
			Random r = new Random();
			
			while (true) {
				try {
					Thread.sleep(r.nextInt(THREAD_WAITING_CEILING));
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				synchronized (lock) {
					while (threadToPrint.intValue() != myID) {
						try {
							lock.wait();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

					System.out.println(myID);
					threadToPrint++;
					if (threadToPrint.intValue() == QUANTITY_OF_THREADS) {
						threadToPrint = 0;
					}
					lock.notifyAll();
				}
			}
		}		
	}
	
	public static void main(String[] args) {
		Thread[] printingThreads = new Thread[QUANTITY_OF_THREADS];
		
		QueueOfThreads qot = new QueueOfThreads();
		
		for (int i = 0; i < QUANTITY_OF_THREADS; i++) {
			printingThreads[i] = new Thread(qot.new PrintingThread(i));
		}
		
		for (int i = 0; i < QUANTITY_OF_THREADS; i++) {
			printingThreads[i].start();
		}
	}
}